/*
 * cve-check-tool.h
 *
 * Copyright (C) 2015-2016 Sergey Popovich <popovich_sergei@mail.ua>.
 *
 * cve-check-tool is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */

#include <stdbool.h>

/**
 * Enumerate to represent possible locking types to imply on the
 * database file
 */
typedef enum {
        LT_READ = 0, /**<Shared lock type */
        LT_WRITE,    /**<Exclusive lock type */
        __LT_MAX
} locktype;

#define LT_MAX (__LT_MAX - 1)

enum { LOCK_WAIT_SECS = 5 * 60, /**<Wait for lock to aquire 5 minutes */
};

/**
 * Initialize lock on the database by opening it's file and saving
 * descriptor for later use by other locking functions
 *
 * @note If database file does not exists it will be created
 *
 * @param db_file Database file to operate on
 * @return True if database file opened successfuly and false overwise
 */
bool cve_db_lock_init(const char *db_file);

/**
 * Finalizes lock usage on database file by closing corresponding
 * file descriptor
 *
 * @note Any locking, if applied to the file descriptor will be released
 */
void cve_db_lock_fini(void);

/**
 * Try to aquire lock of the given type on the previously initialized
 * database file descriptor within given timeout
 *
 * @param lt Lock type to aquire as specified by the enum locktype
 * @param wait Number of seconds to wait for lock before giving up
 * If specified as < 0 then return immediately, 0 means wait
 * indefinitely to aquire lock.
 */
bool cve_db_lock(locktype lt, int wait);

/**
 * Helper routine to aquire shared (read) lock within given timeout
 *
 * @note Calls cve_db_lock() with LT_READ to perform real work
 *
 * @param wait Number of seconds to wait for lock before giving up
 */
static inline bool cve_db_read_lock(int wait)
{
        return cve_db_lock(LT_READ, wait);
}

/**
 * Helper routine to aquire exclusive (write) lock within given timeout
 *
 * @note Calls cve_db_lock() with LT_WRITE to perform real work
 *
 * @param wait Number of seconds to wait for lock before giving up
 */
static inline bool cve_db_write_lock(int wait)
{
        return cve_db_lock(LT_WRITE, wait);
}

/**
 * Releases previously aquired lock from database file
 */
void cve_db_unlock(void);

/*
 * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * c-basic-offset: 8
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * vi: set shiftwidth=8 tabstop=8 expandtab:
 * :indentSize=8:tabSize=8:noTabs=true:
 */
